package com.prelearning.at_springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.prelearning.at_springboot.entity.Published;
import com.prelearning.at_springboot.entity.Unpublish;
import com.prelearning.at_springboot.mapper.UnpublishMapper;
import com.prelearning.at_springboot.service.IPublishedService;
import com.prelearning.at_springboot.service.IUnpublishService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.prelearning.at_springboot.utils.WorkWXAPIUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cgr
 * @since 2022-04-10
 */
@Service
public class UnpublishServiceImpl extends ServiceImpl<UnpublishMapper, Unpublish> implements IUnpublishService {

    @Resource
    private IPublishedService publishedService;

    @Resource
    UnpublishMapper unpublishMapper;

    //初始化需要存入数据库的unpublish对象
    @Override
    public Unpublish init(Unpublish unpublish) {
        unpublish.setUseName(WorkWXAPIUtil.getUserInfo(unpublish.getUserId())[0]);
        unpublish.setPublishStatus(0);
        String[] members =WorkWXAPIUtil.getGroupMember(unpublish.getGroupId());
        assert members != null;
        unpublish.setExpectNumber(members.length-1);
        unpublish.setUnsignedNumber(members.length-1);
        unpublish.setResult(WorkWXAPIUtil.getResult(unpublish.getGroupId()).toString());
        return unpublish;
    }

    //定时刷新数据库调整签到表单的发布状态并存入已发布数据库中
    @Override
    public void refresh() {
        List<Unpublish> unpublishList= list(new QueryWrapper<Unpublish>().orderByDesc("creat_time"));
        for(Unpublish unpublish :unpublishList){
            LocalDateTime startTime=unpublish.getStartTime();
            LocalDateTime nowTime=LocalDateTime.now();
            if(Duration.between( startTime, nowTime).toMillis()>0){
                unpublish.setPublishStatus(1);
                publishedService.saveOrUpdate(unpublish);
                removeById(unpublish.getSignInId());
                WorkWXAPIUtil.postMessage(unpublish.getGroupId());
                System.out.println("\n================transfer one in unpublish================");
            }
        }
        System.out.println("\n------------------------cleaned one time in unpublish------------------------");
    }

    @Override
    public List<Unpublish> getUnpublish(String owner_id) {
        return unpublishMapper.getUnpublish(owner_id);
    }
}
